package com.wnxy.portal.controller;

import cn.hutool.jwt.JWTUtil;
import com.wnxy.portal.common.result.Result;
import com.wnxy.portal.model.vo.CartVo;
import com.wnxy.portal.service.ICartService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private ICartService cartService;

    /**
     * 添加购物车
     */
    @PostMapping("/addCart")
    public Result addCart(Long bookId, @RequestHeader("Authorization")String token) {
        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        cartService.addCart(userId,bookId);
        return Result.ok();
    }

    /**
     * 我的购物车
     */
    @PostMapping("/mycart")
    public Result mycart(@RequestHeader("Authorization")String token) {
        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        CartVo cartVo = cartService.queryCart(userId);
        return Result.ok(cartVo);
    }

    /**
     * 修改数量
     */
    @PostMapping("/changeBuyNum")
    public Result changeBuyNum(Integer bookId,Integer buyCount,@RequestHeader("Authorization")String token) {
        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        cartService.changeBuyNum(userId,bookId,buyCount);
        return Result.ok();
    }
    /**
     * 购物车删除
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer bookId,@RequestHeader("Authorization")String token) {
        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        cartService.deleteById(userId,bookId);
        return Result.ok();
    }


    @PostMapping("/calc")
    public Result calc(@RequestBody Long[] ids, @RequestHeader("Authorization")String token) {
        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        CartVo cartVo = cartService.queryCalc(userId,ids);
        return Result.ok(cartVo);
    }
}
